<template>
  <t-anchor
    @click="handleAnchorClick"
    @change="change"
    :container="getContainer"
    class="custom-anchor"
    ref="customAnchor"
  >
    <template #cursor>
      <div class="text-cursor"></div>
    </template>
    <t-anchor-item
      v-for="item in itemList" :key="item.name"
      :href="'#' + item.name"
      :title="item.title"
    />
  </t-anchor>
</template>

<script>

export default {
  desc: '自定义锚点',
  components: {
  },
  name: 'customAnchor',
  props: {
    /**
     * @Description：锚点容器，定义的ref属性
     * @Date 2023-10-10
     */
    container: {
      type: String,
      default: () => 'formRight'
    },
    /**
     * @Description：锚点列表
     * @Date 2023-10-10
     */
    itemList: {
      type: Array,
      default: () => []
    }
  },
  mounted() {
    if (this.itemList.length > 0) {
      this.$refs.customAnchor.setCurrentActiveLink('#' + this.itemList[0].name)
    }
  },
  data() {
    return {
    }
  },
  methods: {
    // 锚点点击
    handleAnchorClick({ e }) {
      e.preventDefault()
    },

    // 获取锚点容器
    getContainer() {
      if (!this.container || !this.$parent.$refs || !this.$parent.$refs[this.container]) {
        return null
      }
      return this.$parent.$refs[this.container]
    },

    // 锚点改变时触发
    change(currentLink, prevLink) {
      $(this.getContainer()).find(currentLink).addClass('box-title-active')
      if (prevLink != null) {
        $(this.getContainer()).find(prevLink).removeClass('box-title-active')
      }
    }
  },
  watch: {
    // 监听表单设置本组件的值
    itemList: {
      immediate: true, // 初始创建 watch 时立即执行回调函数
      deep: true, // 监听到对象里面的值的变化
      handler() {
        if (this.itemList.length > 0 && this.$refs.customAnchor) {
          this.$refs.customAnchor.setCurrentActiveLink('#' + this.itemList[0].name)
          setTimeout(() => {
            this.change('#' + this.itemList[0].name,null)
          }, 500)
        }
      },
    }
  },
  computed: {
  }
}
</script>

<style lang="scss">
.custom-anchor{
  width: auto !important;
  background: none !important;
  .t-is-active {
    a {
      color: #278259;
    }
    .text-cursor {
      background-color:  #278259;
    }
  }
}
.form-layout .text-cursor {
  background-color:  #278259 !important;
}

</style>
